package org.ttitfly.workflow.engine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ttitfly.workflow.exception.DuplicateProcessDefineException;


/**
 * 流程工厂基本功能实现
 * 
 * @author 潘海春
 * @version 2009-9-22
 */
public class AbstractProcessFactory implements ProcessFactory {

	/**
	 * 定义数据
	 */
	private Map<String, List<Process>> data = new HashMap<String, List<Process>>();

	/**
	 * 添加流程定义
	 * 
	 * @param process
	 */
	protected void put(Process process) {
		String processName = process.getName();
		float version = process.getVersion();
		List<Process> processes = data.get(processName);
		if (processes == null) {
			processes = new ArrayList<Process>();
			processes.add(process);
			data.put(processName, processes);
		} else {
			for (Process p : processes) {
				if (p.getVersion() == version) {
					throw new DuplicateProcessDefineException(processName, version);
				}
			}
			processes.add(process);
		}
	}

	@Override
	public Process getProcess(String processName) {
		List<Process> processes = data.get(processName);
		if (processes != null && !processes.isEmpty()) {
			Process process = processes.get(0);
			for (Process p : processes) {
				if (p.getVersion() > process.getVersion()) {
					process = p;
				}
			}
			return process;
		}
		return null;
	}

	@Override
	public Process getProcess(String processName, float version) {
		List<Process> processes = data.get(processName);
		if (processes != null && !processes.isEmpty()) {
			for (Process process : processes) {
				if (process.getVersion() == version) {
					return process;
				}
			}
		}
		return null;
	}

}
